<!-- 整个系统的用户 -->
<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <!--<a-button  type="primary" preIcon="ant-design:plus-outlined"  v-auth="'user:add'" @click="handleCreate" > 新增</a-button> -->
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增</a-button>
        <a-button type="primary" preIcon="ant-design:import-outlined" @click="onExportXls"> 导出</a-button>
        <a-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</a-button>
        <a-button type="primary" @click="openModal(true, {})" preIcon="ant-design:hdd-outlined"> 回收站</a-button>
        <JThirdAppButton biz-type="user" :selected-row-keys="selectedRowKeys" syncToApp syncToLocal @sync-finally="onSyncFinally" />
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="i-ant-design:delete-outlined" />
                删除
              </a-menu-item>
              <a-menu-item key="2" @click="batchFrozen(2)">
                <Icon icon="i-ant-design:lock-outlined" />
                冻结
              </a-menu-item>
              <a-menu-item key="3" @click="batchFrozen(1)">
                <Icon icon="i-ant-design:unlock-outlined" />
                解冻
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="i-mdi:chevron-down" />
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
    </BasicTable>
    <UserForm @register="registerForm" @success="handleSuccess" />
    <UserDetail @register="registerDetail" @success="handleSuccess" />
    <PasswordModal @register="registerPasswordModal" @success="reload" />
    <UserRecycleBinModal @register="registerModal" @success="reload" />
  </div>
</template>

<script lang="ts" name="system-user" setup>
  //ts语法
  import { ref, computed, unref } from "vue"
  import { BasicTable, TableAction, ActionItem } from "/@/components/Table"
  import UserForm from "./UserForm.vue"
  import UserDetail from "./UserDetail.vue"
  import UserRecycleBinModal from "./UserRecycleBinModal.vue"
  import PasswordModal from "./PasswordModal.vue"
  import JThirdAppButton from "/@/components/jeecg/thirdApp/JThirdAppButton.vue"
  import { useDrawer } from "/@/components/Drawer"
  import { useListPage } from "/@/hooks/system/useListPage"
  import { useModal } from "/@/components/Modal"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { columns, searchFormSchema } from "./user.data"
  import { list, deleteUser, batchDeleteUser, getImportUrl, getExportUrl, frozenBatch } from "./user.api"
  import { Icon } from "/@/components/Icon"
  // import { usePermission } from '/@/hooks/web/usePermission'
  // const { hasPermission } = usePermission();

  const { createMessage, createConfirm } = useMessage()

  const selectRows = ref([])
  const [registerForm, { openDrawer: openInputForm }] = useDrawer()
  const [registerDetail, { openDrawer: openDetail }] = useDrawer()
  const [registerModal, { openModal }] = useModal()
  const [registerPasswordModal, { openModal: openPasswordModal }] = useModal()

  // 列表页面公共参数、方法
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    designScope: "user-list",
    tableProps: {
      title: "用户列表",
      api: list,
      bordered: false,
      columns: columns,
      size: "small",
      formConfig: {
        schemas: searchFormSchema,
      },
      actionColumn: {
        width: 160,
        title: "操作",
        dataIndex: "action",
        fixed: "right",
        slots: { customRender: "action" },
      },
      beforeFetch: (params) => {
        return Object.assign({ column: "createTime", order: "desc" }, params)
      },
    },
    exportConfig: {
      name: "用户列表",
      url: getExportUrl,
    },
    importConfig: {
      url: getImportUrl,
    },
  })

  const [registerTable, { reload, updateTableDataRecord }, { rowSelection, selectedRowKeys }] = tableContext

  function handleCreate() {
    console.time("user-drawer")
    openInputForm(true, {
      isUpdate: false,
      showFooter: true,
    })
  }

  async function handleEdit(record: Recordable) {
    console.time("user-drawer")
    openInputForm(true, {
      record,
      isUpdate: true,
      showFooter: true,
    })
  }

  async function handleDetail(record: Recordable) {
    openDetail(true, { record })
  }

  async function handleDelete(record) {
    if (record.isAdmin) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    await deleteUser({ id: record.id }, reload)
  }

  async function batchHandleDelete() {
    let hasAdmin = unref(selectRows).filter((item) => item.isAdmin)
    if (unref(hasAdmin).length > 0) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    await batchDeleteUser({ ids: selectedRowKeys.value }, () => {
      selectedRowKeys.value = []
      reload()
    })
  }

  function handleSuccess({ isUpdate, values }) {
    reload()
    if (isUpdate) {
      updateTableDataRecord(values.id, values)
      createMessage.success("编辑成功")
    } else {
      createMessage.success("新增成功")
    }
  }

  /**
   * 打开修改密码弹窗
   */
  function handleChangePassword(userName, id) {
    openPasswordModal(true, { userName, id })
  }

  /**
   * 冻结解冻
   */
  async function handleFrozen(record, status) {
    if (record.isAdmin) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    await frozenBatch({ ids: record.id, status: status }, reload)
  }
  /**
   * 批量冻结解冻
   */
  function batchFrozen(status) {
    let hasAdmin = unref(selectRows).filter((item) => item.isAdmin)
    if (unref(hasAdmin).length > 0) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    createConfirm({
      iconType: "warning",
      title: "确认操作",
      content: "是否" + (status == 1 ? "解冻" : "冻结") + "选中账号?",
      onOk: async () => {
        await frozenBatch({ ids: unref(selectedRowKeys).join(","), status: status }, reload)
      },
    })
  }

  /**
   *同步钉钉和微信回调
   */
  function onSyncFinally({ isToLocal }) {
    // 同步到本地时刷新下数据
    if (isToLocal) {
      reload()
    }
  }

  const checkeUser = (record) => {
    // 不能操作租户拥有者, 其余都可以操作
    return record.roleList
      .map((e) => e.roleCode)
      .join(",")
      .includes("owner")
  }

  function getTableAction(record): ActionItem[] {
    return [
      {
        label: "删除",
        ifShow: () => !checkeUser(record),
        color: 'error',
        popConfirm: {
          title: "是否确认删除",
          confirm: handleDelete.bind(null, record),
        },
      },
      {
        label: "详情",
        onClick: handleDetail.bind(null, record),
      },
    ]
  }

  function getDropDownAction(record): ActionItem[] {
    return [
      {
        label: "密码",
        onClick: handleChangePassword.bind(null, record.userName, record.id),
        ifShow: () => !checkeUser(record),
      },
      {
        label: "编辑",
        onClick: handleEdit.bind(null, record),
        ifShow: () => !checkeUser(record),
      },
      {
        label: "冻结",
        ifShow: !checkeUser(record) && record.status == 1,
        popConfirm: {
          title: "确定冻结吗?",
          confirm: handleFrozen.bind(null, record, "2"),
        },
      },
      {
        label: "解冻",
        ifShow: !checkeUser(record) && record.status == 2,
        popConfirm: {
          title: "确定解冻吗?",
          confirm: handleFrozen.bind(null, record, "1"),
        },
      },
    ]
  }
</script>

<style scoped></style>
